/**
 * Created by levy on 2016/12/19.
 */
import mui from '../../lib/js/mui'

const re = /(\\?|&)token=([^&]+)($|&)/

function getToken() {
  if(!token) {
    let query = location.search.substr(1)

    let arr = query.match(re);

    if (arr && arr.length) {
      token = decodeURI(arr[2]);
    }
  }

  return token
}

/**
 * 传个数字示意一下. 后台改了接口, 根据token获取userId
 * @returns {number}
 */
function getUserId() {
  return 21919
}

function ajax(options, successCb, errorCb) {
  let newUrl = options.url,
    token = getToken()

  if (!token) {
    //mui.alert('没有token, 使用mock token b8abed643a5743f681882264002a057b')
    // token 的获取
    // http://10.64.18.8/login
    // 账号: 43004
    // 密码: hy79727972
    token = '81f0100e751d44329fdf29e185f5e1e7'
  }

  newUrl = newUrl.indexOf('?') > -1 ? newUrl + '&token=' + token : newUrl + '?token=' + token

  if (location.host.indexOf('localhost') == -1)  // 非开发使用template.html上的前缀, 开发则使用代理
      newUrl = apiPrefix + newUrl

  options.url = newUrl
  if (successCb)
    options.success = successCb

  if (errorCb)
    options.error = errorCb
  else
    options.error = (xhr, status, err) => {
      let state = xhr.status

      if (state == 401) {
        console.error('缺少token')
        mui.alert('页面跳转异常', function () {
          history.back()
        })
      }

      else if (state == 403) {
        console.error('无效的token')
        mui.alert('员工工号有误', function () {
          history.back()
        })
      }

      else
          console.error(xhr)

    }

  mui.ajax(options)
}


//网络请求
function fetch(url, params) {
  let options = {
    contentType: 'application/json',
    timeout: 25000
  }
  options.url = url

  if (params) {
    for (let key in params) options[key] = params[key]
  }

  return new Promise((resolve, reject) => {
    ajax(options, data => resolve(data), err => {
      console.error(err);
      reject(err)
    })
  })
}



//sql语句勾转成.
function parseSql(sql = "") {
  return sql.replace(/√/g, "'");
}
function getLocaleDefault() {
  return 'zh-CN'
}
export {
  ajax, getUserId, fetch, getLocaleDefault,
  parseSql
}

